using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace LiteNote
{

    class Utility
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, uint cchBuffer);

        [DllImport("user32.dll")]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder value, int cch);

        [DllImport("user32.dll")]
        public static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);

        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hwnd);

        [DllImport("user32.dll")]
        public static extern int SetClassLong(IntPtr hwnd, int nIndex, int newLog);

        [DllImport("user32.dll")]
        public static extern int GetDoubleClickTime();


        public static string GetShortPathName(string fileName)
        {
            StringBuilder shortNameBuffer = new StringBuilder(256);
            uint bufferSize = (uint)shortNameBuffer.Capacity;
            uint result = GetShortPathName(fileName, shortNameBuffer, bufferSize);
            if (result != 0) {
                return shortNameBuffer.ToString();
            }
            return fileName;
        }

        // 是否为正常的txt后缀
        public static bool IsTextFile(string filename)
        {
            if (!File.Exists(filename))
                return false;

            string ext = Path.GetExtension(filename);
            if (ext.ToLower() == ".txt")
                return true;
            if (ext.ToLower() == ".md")
                return true;

            return false;
        }

        // 是否是正常的目录
        public static bool IsNormalFold(string path)
        {
            if (path.Length == 0)
                return false;

            if (!Directory.Exists(path))
                return false;

            string s = Path.GetFileName(path).ToLower();
            if (s == ".git" || s == "trash")
                return false;
            if (s.EndsWith(".app"))
                return false;

            string[] logics = Directory.GetLogicalDrives();

            if (!logics.Contains(path.ToUpper())) {

                DirectoryInfo info = new DirectoryInfo(path);
                FileAttributes a = info.Attributes & FileAttributes.Hidden;
                if (a == FileAttributes.Hidden) {
                    return false;
                }

                //info.Attributes == (FileAttributes.Hidden | FileAttributes.System | FileAttributes.Directory)
                // 不仅c:\ d:\是上面这三个属性，系统的隐藏文件也是这三个属性
            }

            return true;
        }

        public static string GetFormText(IntPtr hWnd)
        {
            StringBuilder s = new StringBuilder(512);
            GetWindowText(hWnd, s, s.Capacity);
            return s.ToString();
        }

        public static void EditInApp(string app, string filename)
        {
            if (File.Exists(filename)) {
                string s = GetShortPathName(filename);

                if (app.EndsWith("gvim.exe")) {
                    //s =  + s;
                    s = string.Format("-p --remote-tab-silent \"{0}\"", s);
                }

                Process p = new Process();
                p.StartInfo.FileName = app;
                p.StartInfo.Arguments = s;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;

                p.Start();
                p.Close();
            }
        }

        public static void OpenInExplorer(string filename)
        {
            Process p = new Process();
            p.StartInfo.FileName = "OpenInExplorer.exe";
            p.StartInfo.Arguments = GetShortPathName(filename);
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;

            p.Start();
            p.Close();
        }

        /*
         * 0 空文件
         * 1 VimCrypt~加密
         * 2 正常文本
        */
        public static int GetFileStyle(string filename)
        {
            try {
                using (var stream = new BinaryReader(new FileStream(filename, FileMode.Open))) {
                    byte[] buf = new byte[9];

                    if (stream.Read(buf, 0, buf.Length) != 0) {
                        string s = Encoding.ASCII.GetString(buf);
                        if (s == "VimCrypt~")
                            return 1;
                    } else {
                        return 0;
                    }
                    return 2;
                }


            } catch (Exception e) {
                return 0;
            }
        }

        // 在path文件夹下找一个不存在的文件名
        public static string GetNoExistNote(string path)
        {
            string name = Path.Combine(path, "新建笔记.md");

            if (!File.Exists(name))
                return name;

            int i = 2;
            while (true) {
                name = Path.Combine(path, String.Format("新建笔记{0}.md", i));
                if (!File.Exists(name))
                    return name;

                ++i;
            }
        }

        // 在path文件夹下找一个不存在的文件夹名
        public static string GetNoExistFold(string path)
        {
            string name = Path.Combine(path, "新建文件夹");

            if (!Directory.Exists(name))
                return name;

            int i = 2;
            while (true) {
                name = Path.Combine(path, String.Format("新建文件夹{0}", i));

                if (!Directory.Exists(name))
                    return name;

                ++i;
            }
        }

        // 在path文件夹下找一个不存在的name文件
        public static string GetNoExistsImgName(string path, string name)
        {
            string one = Path.Combine(path, name);
            if (!File.Exists(one))
                return one;

            int i = 2;
            while (true) {
                one = Path.Combine(path, string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(name), i, Path.GetExtension(name)));

                if (!File.Exists(one))
                    return one;
                ++i;
            }

        }

        public static void log2(string path, string text)
        {
            //File.WriteAllText
        }
    }


}
